﻿using System;
using System.Linq;
using System.Web.Mvc;
using Infrastructure.Persistence;
using SocialFront.Core.Commands.FooCommands;
using SocialFront.Core.Domain;
using SocialFront.Core.Mapping.FooMappers;
using SocialFront.Core.Queries.FooQueries;
using SocialFront.Web.Models;
using SocialFront.Services.Application.ViewModels;

namespace SocialStore.Web.Controllers
{
    public class FooController : Controller
    {
        private int _pagesize = 10;

        public int PageSize
        {
            get { return _pagesize; }
            set { _pagesize = value; }
        }

        public int StartRow { get; set; }

        private readonly IRepository _repository;
        
        public FooController(IRepository repository)
        {
            _repository = repository;
        }

        //
        // GET: /Foo/
        public ActionResult Index()
        {
            return View(new FooSearchViewModel());
        }

        [HttpPost]
        [OutputCache(Duration=0)]
        public ActionResult Foos(FooSearchViewModel model)
        {
            var view = new FooView() { Foo1 = model.SearchTerm };

            var query = new FooWildcardQuery(_repository);

            long count = 0;
            var response = query.Where(view.ConvertToFoo())
                                .OnCount(x => count = x)
                                .PageOfResults();

            if (response.Success)
                return Json(new 
                            { 
                                Success     = true, 
                                Data        = response.List.ConvertToFooView(),
                                TotalPages  = response.List.Count() / PageSize, 
                                ItemCount   = response.List.Count(),
                                CurrentPage = StartRow
                            });
                
            return Json("Issue");
        }

        [HttpGet]
        public ViewResult Update(int id)        
        {
            var response = new FooWildcardQuery(_repository)
                                 .Where(new Foo { Id = id})
                                 .First();

            if (response.Success)
                return View(response.Result.ConvertToFooView());
            else
                throw new NotImplementedException();
        }

        [HttpPost]
        [OutputCache(Duration = 0)]
        public ActionResult Update(FooView view)
        {
            // Option 1.
            var command = 
                new UpdateFooCommand(_repository) { Foo = view.ConvertToFoo() };
            
            var response = command.Execute();
            
            if (response.Success)
                return Json(new { Success = true });

            return Json("Issue");
        }
    }
}
